import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import {
  cancelGive,
  confirmGive,
  getCouponDetail,
  getCouponReceiveCode,
  getCouponStatus,
  getCouponSyncConfig
} from "@src/api/coupon";
import $color from "@src/common/color";
import dayjs from "dayjs";
import pageHandleUtil from "@src/common/pageHandleUtil";
import base from "@src/store/base";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['businessName']
  }],
  properties: {
    couponCode: {
      type: String,
      value: ""
    },
    couponStatus: {
      type: Number,
      value: 1
    },
  },
  data: {
    navHeight: 80,
    loading: false,
    couponStatus: null,
    couponDetail: null,
    isExpired: false,
    qrNumber: '',
    pageBgColor: {},
    eanCode: "",
    qrCode: "",
    couponInstructionArr: [],
  },
  observers: {
    'couponDetail.status, isExpired': function (status, isExpired) {
      if (status === 2) {
        // 不可用
        this.setData({couponStatus: 2})
      } else if (isExpired) {
        this.setData({couponStatus: 4})
      }
      this.setData({couponStatus: status})
    }
  },
  methods: {
    onLoad() {
      // 禁用右上角转发
      wx.hideShareMenu();
    },
    onShow() {
      if (this.data.couponStatus === 1 && !this.data.interTime) {
        let interTime = setInterval(() => {
          this.couponStatusReq();
        }, 2000)
        this.setData({interTime: interTime})
      }
    },
    onHide() {
      this.clear();
    },
    onUnload() {
      this.clear();
    },
    // 转发给微信好友(不能写到method里)
    onShareAppMessage(res) {
      wx.showShareMenu({withShareTicket: true});
      if (res.from === "button") {
        this.setData({sendFriendModal: false})
        this.confirmGiveReq();
      }
      return {
        title: "送你一张优惠券，点击消息立即领取。",
        path: `pages/receiveCoupon/main?receiveCode=${this.data.receiveCode}`,
        imageUrl: this.data.shareImg
      };
    },
    onLogin() {
      this.setData({login: true})
      this.couponDetailReq().then(() => {
        this.receiveCodeReq();
        if (this.data.couponStatus === 1 && !this.data.interTime) {
          let interTime = setInterval(() => {
            this.couponStatusReq();
          }, 2000)
          this.setData({interTime: interTime})
        }
      })
    },
    // 券的详情
    couponDetailReq() {
      let data = {couponCode: this.data.couponCode};
      return getCouponDetail(data).then(res => {
        let {couponDetail, availablePeriods, isExpired, eanCode, qrCode} = res.data;
        // 时段可使用渲染
        let couponInstructionArr = []
        if (couponDetail.hasTimeLimit) {
          // 是否全部时段可用
          if (availablePeriods.length > 0) {
            if (availablePeriods[0].timeType === "week") {
              couponInstructionArr = pageHandleUtil.dillCouponWeek(availablePeriods);
            } else {
              couponInstructionArr = pageHandleUtil.dillCouponDay(availablePeriods);
            }
          }
        } else {
          couponInstructionArr.push({returnString: `全部时段可用`, timeString: ``});
        }
        couponInstructionArr.push({returnString: couponDetail.description, timeString: ``});
        let qrNumber = couponDetail.couponCode.replace(/(.{4})/g, "$1 ")
        if (couponDetail.expireTime) {
          couponDetail.expireTime = dayjs(couponDetail.expireTime).subtract(1, "seconds").format("YYYY-MM-DD")
        }
        let pageBgColor = $color.getThemeObj(couponDetail.color);
        wx.setBackgroundColor({backgroundColorTop: pageBgColor.color, backgroundColorBottom: pageBgColor.color});
        this.setData({
          loading: false,
          couponDetail,
          couponInstructionArr,
          qrNumber,
          isExpired,
          eanCode,
          qrCode,
          pageBgColor
        });
      })
    },
    couponStatusReq() {
      let data = {
        couponCode: this.data.couponCode
      };
      getCouponStatus(data).then(res => {
        if (res.code === 0) {
          if (res.data.status === 2) {
            // 已经使用
            if (this.data.couponStatus === 1) {
              // 之前卡券状态为1的时候出来
              this.setData({haoDaModal: true})
            }
            this.couponDetailReq();
            this.clear();
          } else if (res.data.isExpired) {
            this.couponDetailReq();
            this.clear();
          }
        }
      })
    },
    handleCloseFinish() {
      this.setData({haoDaModal: false})
    },
    clear() {
      if (this.data.interTime) {
        clearInterval(this.data.interTime);
        this.setData({interTime: null})
      }
    },
    toSendFriend() {
      // 弹出modal框
      this.setData({sendFriendModal: true})
    },
    receiveCodeReq() {
      let data = {couponCode: this.data.couponDetail.couponCode}
      return getCouponReceiveCode(data).then(res => {
        if (res.code === 0) {
          this.setData({receiveCode: res.data})
        }
      })
    },
    // 更改券的状态为赠送
    confirmGiveReq() {
      let data = {
        receiveCode: this.data.receiveCode
      };
      confirmGive(data).then(res => {
        if (res.code === 0) {
          this.couponDetailReq();
          this.clear();
        }
      })
    },
    syncConfigReq() {
      if (this.data.couponDetail.syncWx) {
        return;
      }
      let data = {
        couponCode: this.data.couponCode
      };
      wx.showLoading({title: "同步中...", mask: true});
      getCouponSyncConfig(data).then(res => {
        setTimeout(()=> {
          wx.hideLoading();
        }, 200)
        wx.addCard({
          cardList: [{cardId: res.data.cardId, cardExt: res.data.cardExt}],
          success: (res) => {
            if (res.cardList[0].isSuccess) {
              this.couponDetailReq();
              wx.showToast({title: "同步卡包成功", icon: "success", duration: 3000});
            }
          }, cancel: (res) => {
            wx.showToast({title: "您取消了同步卡包", icon: "none", duration: 4000});
          },
          fail: (res) => {
            this.couponDetailReq();
            wx.showToast({title: "同步卡包失败" + res, icon: "none", duration: 4000});
          }
        });
      }).catch(() => {
        wx.hideLoading();
      })
    },
    couponGiveCancelReq() {
      // 取消赠送中的卡券
      let data = {
        couponCode: this.data.couponDetail.couponCode
      };
      cancelGive(data).then(res => {
        this.couponDetailReq();
      })
    },
    haoDaBtn() {
      // 好哒按钮
      getApp().$router.redirectTo({name: 'member/myCoupon'})
    },
    useInstruction() {
      this.selectComponent("#use-instruction").open({
        passRemark: this.data.couponDetail.remark,
        couponInstructionArr: this.data.couponInstructionArr
      });
    },
    sendFriendMBtn() {
      // 好哒按钮
      this.setData({sendFriendModal: false})
    },
    handleStop() {
      return false;
    },
    toAllShopAvailable() {
      if (this.data.couponDetail.isAllShopAvailable) {
        this.selectComponent("#shop-list-dialog").dialogShow({allShopCanUse: 1});
      } else {
        this.selectComponent("#shop-list-dialog").dialogShow({
          allShopCanUse: 2,
          couponId: this.data.couponDetail.couponId
        });
      }
    },
    handleGenPoster(e) {
      this.setData({"shareImg": e.detail})
    },
  }
})
